// search_term.js 
 
const elasticsearch = require('elasticsearch');
 
const client = new elasticsearch.Client({
    host: '127.0.0.1:9200',
    log: 'error'
});
 
const search = function search(index, body) {
    return client.search({index: index, body: body});
};
 
module.exports = function searchTerm(req) {
    let dyn1 = req.dynasty.join(" ");
    let reg1 = new RegExp('国','');
    let reg2 = new RegExp('代','');
    let reg4 = new RegExp('朝','');
    let dyn2 = dyn1.replace(reg1, "");
    let dyn3 = dyn2.replace(reg2, "");
    let dyn4 = dyn3.replace(reg4, "");
    for(let i = 0; i < req.museum.length; i++) {
        req.museum[i] = req.museum[i].substr(0,2);
        console.log(i);
    }

    let muse1 = req.museum.join(" ");
    let reg3 = new RegExp('安','');
    let muse = muse1.replace(reg3,"");
    
    let name = req.name.join(" ");
    console.log(muse);
    console.log(dyn4);
    let body = {
        size: 500,
        from: 0,
        query: {
            bool : {
               must : [
                    {
                        match:  {
                            dynasty: {
                                query:  dyn4 === '' ? '史前 夏 商 周 春秋·战国 秦·汉 三国 晋 南北朝 隋·唐 五代十国 宋 金 元 明 清' : dyn4,
                                operator : 'or'
                            }
                        }
                    },
                    {
                        match:  {
                            name: {
                                query:  name === '' ? '瓶 碗 罐 杯 盘 壶' : name,
                                operator : 'or'
                            }
                        }
                    },
                    {
                        match:  {
                            museum: {
                                query: muse === '' ? '上海 故宫 安徽' : muse,
                                operator : 'or'
                            }
                        }
                        
                    }
                ]
            }

        }
    };
    let result = search('data', body);
    //console.log(result);
    return result;
};